package cn.liwq.demo.java.raw.scanner;

import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * <p>Project: demo-common </p>
 * <p>Function:  </p>
 * <p>Description:  </p>
 * <p>Copyright: Copyright(c) 2018 Ucarinc </p>
 * <p>Company: Ucarinc </p>
 *
 * @author weiqiang.li@ucarinc.com
 * @version 1.0
 * @date 2018-08-16 11:23:11
 */
public class ClassScanner {

    private List<Class<?>> classList;

    private ClassLoader classLoader;

    private Class[] filerClassArr;

    private final static String FILE_PROTOCOL = "file";

    private final static String JAR_PROTOCOL = "jar";

    private final static String CLASS_SUFFIX = ".class";

    public ClassScanner() {
        classList = new ArrayList<>();
        classLoader = Thread.currentThread().getContextClassLoader();
    }

    public void loadClass(String pacakgeName, Class<?>... filter) {
        if (filter.length > 0) {
            filerClassArr = filter;
        } else {
            filerClassArr = new Class[]{};
        }

        URL url = classLoader.getResource(toggleDotSlash(pacakgeName));
        String protocol = url.getProtocol();
        if (FILE_PROTOCOL.equals(protocol)) {
            loadClassFromFile(pacakgeName);
        } else if (JAR_PROTOCOL.equals(protocol)) {
            loadClassFromJar(pacakgeName);
        }
        System.out.printf("共加载%d个类\r\n", classList.size());
    }

    private void loadClassFromFile(String pacakgeName) {
        URI uri = null;
        try {
            uri = classLoader.getResource(toggleDotSlash(pacakgeName)).toURI();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        File file = new File(uri);
        file.listFiles(f -> {
            if (f.isDirectory()) {
                loadClassFromFile(pacakgeName + "." + f.getName());
            } else if (f.getName().endsWith(CLASS_SUFFIX)) {
                Class<?> clazz = null;
                try {
                    clazz = classLoader.loadClass(pacakgeName + "." + removeClassExt(f.getName()));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                if (!isFiltered(clazz)) {
                    System.out.println("加载本地类: " + clazz.getName());
                    classList.add(clazz);
                }

                return true;
            }
            return false;
        });
    }

    private void loadClassFromJar(String pacakgeName) {
        String pathName = toggleDotSlash(pacakgeName);
        JarFile jarFile = null;
        URL url = classLoader.getResource(pathName);
        try {
            JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
            jarFile = jarURLConnection.getJarFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Enumeration<JarEntry> jarEntries = jarFile.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            String jarEntryName = jarEntry.getName();
            if (jarEntryName.contains(pathName) && !jarEntryName.equals(pathName + "/")) {
                if (jarEntry.isDirectory()) {
                    String className = toggleDotSlash(jarEntryName.substring(0, jarEntryName.length() - 1));
                    loadClassFromJar(className);
                } else if (jarEntryName.endsWith(CLASS_SUFFIX)) {
                    Class<?> clazz = null;
                    try {
                        clazz = classLoader.loadClass(toggleDotSlash(removeClassExt(jarEntryName)));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    if (!isFiltered(clazz)) {
                        System.out.println("加载jar包类: " + clazz.getName());
                        classList.add(clazz);
                    }
                }
            }
        }
    }

    public List<Class> getClassList(String packageName) {
        List<Class> classList = new ArrayList<>();
        try {
            List<File> fileList = new ArrayList<>();
            Enumeration<URL> enumeration = classLoader.getResources(toggleDotSlash(packageName));
            while (enumeration.hasMoreElements()) {
                URL url = enumeration.nextElement();
                fileList.add(new File(url.getFile()));
            }
            for (File file : fileList) {
                classList.addAll(findClass(file, packageName));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return classList;
    }

    private List<Class> findClass(File file, String packageName) {
        List<Class> classList = new ArrayList<>();
        if (!file.exists()) {
            return  classList;
        }
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isDirectory()) {
                findClass(f, packageName + "." + f.getName());
            } else if (f.getName().endsWith(CLASS_SUFFIX)) {
                Class<?> clazz = null;
                try {
                    clazz = Class.forName(packageName + "." + removeClassExt(f.getName()));
                    classList.add(clazz);
                    System.out.println("load class : " + clazz.getName());
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return classList;
    }

    private boolean isFiltered(Class<?> clazz) {
        if (filerClassArr.length == 0) {
            return false;
        }
        for (Class filterClass : filerClassArr) {
            if (filterClass.isAssignableFrom(clazz)) {
                return false;
            }
        }
        return true;
    }

    private String toggleDotSlash(String str) {
        return str.contains(".") ? str.replaceAll("\\.", "/") : str.replaceAll("/", ".");
    }

    private String removeClassExt(String pathName) {
        int pos = pathName.lastIndexOf(".");
        return pathName.substring(0, pos);
    }

    public static void main(String[] args) {
        ClassScanner classScanner = new ClassScanner();
//        classScanner.loadClass("cn.liwq.demo.java", Note.class);
//        classScanner.loadClass("net.sf.cglib");
        classScanner.getClassList("cn.liwq.demo.java");
        classScanner.getClassList("net.sf.cglib");
    }
}
